package com.lhz.collector.service;

import com.lhz.collector.common.RestfulResult;
import com.lhz.collector.entity.User;
import com.lhz.collector.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

/**
 * Created by LHZ on 2017/3/30.
 */
@Service
public class UserServiceImpl implements UserService{
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Override
    public User getByUsername(String username) {
        return userMapper.selectByUsername(username);
    }

    @Override
    public RestfulResult register(User user) {
        RestfulResult restfulResult = new RestfulResult();
        if(userMapper.selectByUsername(user.getUsername())==null){
            //对密码进行加密
            user.setPassword(passwordEncoder.encode(user.getPassword()));
            if(userMapper.insert(user)>0){
                restfulResult.setStatusCode(RestfulResult.STATUS_CODE_SUCCESS);
                restfulResult.setMessage("注册成功");
            }else{
                restfulResult.setMessage("注册失败");
            }
        }else{
            restfulResult.setMessage("用户名已存在");
        }
        return restfulResult;
    }

    @Override
    public RestfulResult changePassword(String username,String oldPassword,String newPassword) {
        RestfulResult restfulResult = new RestfulResult();
        User user = userMapper.selectByUsername(username);
        if (user == null) {
            restfulResult.setMessage("用户名不存在");
        } else {
            if (passwordEncoder.matches(oldPassword, user.getPassword())) {
                user.setPassword(passwordEncoder.encode(newPassword));
                if (userMapper.updatePassword(user)>0) {
                    restfulResult.setStatusCode(RestfulResult.STATUS_CODE_SUCCESS);
                    restfulResult.setMessage("修改成功");
                } else {
                    restfulResult.setMessage("修改失败");
                }
            } else {
                restfulResult.setMessage("旧密码错误");
            }
        }
        return restfulResult;
    }

}
